(function(){

    var downloadlinks = document.querySelector(".download-box > .btn-wrap"),
        hasdownloadlink = downloadlinks && downloadlinks.length > 0,
        pickcode = /https?:\/\/115\.com\/file\/([a-zA-Z0-9]+)/.exec(document.location.href),
        pickcode = pickcode ? pickcode[1] : null,
        CRLF = "\r\n";

    if(/*!hasdownloadlink && */pickcode){
    	var mainWrapper = document.createElement("div");
    	var main = document.createElement("div");
    	var loading = document.createElement("div");
    	var loadingTitle =  document.createElement("div");
		var loadingStatus =  document.createElement("div");
    	var loadingPicURL = chrome.extension.getURL("imgs/loading.gif");
    	var successPicURL = chrome.extension.getURL("imgs/success.png");
		var failPicURL = chrome.extension.getURL("imgs/error.png");
		var warningPicURL = chrome.extension.getURL("imgs/warning.png");
    	var closePicURL = chrome.extension.getURL("imgs/close.png");
		

        //越狱相关函数
        var jailbreakMessage = function( title,result ){
            loadingTitle.innerHTML = title;
            loadingStatus.innerHTML = result;
        }

        var jailbreakSuccess = function( result ){
            jailbreakMessage("越狱成功",result);
			loading.style.backgroundImage="url(\""+successPicURL+"\")";
			showCloseBtn();
		}

        var jailbreakFail = function( result ){
            jailbreakMessage("越狱失败",result);            
    	    loading.style.backgroundImage="url(\""+failPicURL+"\")";
			showCloseBtn();
        }

        var jailbreakWarning = function( result ){
            jailbreakMessage("仍在进行",result);            
    	    loading.style.backgroundImage="url(\""+warningPicURL+"\")";
			showCloseBtn();
        }

        var jailbreaking = function( status ){
            jailbreakMessage("越狱中",status);   
        }
		
		var showCloseBtn = function(){
			var close = mydialog.getCloseBtn();
			close.style.display="block";
			close.style.opacity="0";
			setTimeout(function(){
				close.style.opacity="1";
			},0);
		}

		var initCloseBtn = function(){
		    mydialog.getCloseBtn().style.backgroundImage="url(\""+closePicURL+"\")";
		}

    	mainWrapper.setAttribute(
    		"style",
    		"width:276px;height:132px;-webkit-border-radius:8px;background:-webkit-gradient(linear,left top,left bottom,from(#dfe1e7),to(#babfcb));border-top:1px solid #6b6b6b;border-left:1px solid #585858;border-bottom:1px solid #424242;border-right:1px solid #595959;-webkit-box-shadow:1px 1px 6px #000;");
    	main.setAttribute(
    		"style",
    		"width:270px;height:126px;position:relative;top:3px;left:3px;-webkit-border-radius:8px;background:#1c2c54;"
    	);

        main.setAttribute("class","dialogmain");

    	loading.setAttribute(
    		"style",
    		"width:100%;height:100%;font-family:'Microsoft YaHei';text-align:center;background:url('"+loadingPicURL+"') no-repeat 50% 75%"
    	);

    	loadingTitle.setAttribute(
    		"style",
    		"width:100%;height:48px;line-height:48px;font-size:16px;color:#fff;"
    	);

    	loadingStatus.setAttribute(
    		"style",
    		"width:100%;height:16px;line-height:16px;font-size:12px;color:#999;position:relative;top:-5px;"
    	);

    	loading.appendChild(loadingTitle);
    	loading.appendChild(loadingStatus);
    	main.appendChild(loading);
        mainWrapper.appendChild(main);
    	mydialog = new dialog(document.body,{contentdom:mainWrapper,modal:true});
    	mydialog.show();
		initCloseBtn();

	    window.addEventListener("resize",function(){
	    	mydialog.update();
        },false);

    	//获取实际下载链接地址
        jailbreaking("请稍候...");
		var responseReceived = false;
		//
		setTimeout(function(){//5秒正常时间超时提示
			if(!responseReceived){
				jailbreakWarning("超过正常需要的时间...");
			}
		},5*1000);
        //

        chrome.extension.sendRequest({action:"geturl",urloption:{
                        host:"u.115.com",
						uri :"/?",
						headers :  "Cookie: "+ "OOFL=115jailbreak; OOFA=%250D%250ETV_V%2508%250C%2506%2506%250D%2508W%250BZP%2540%255D%2507%250F%2503%2506%2507Q%2507TV%255CZXxBD%2519%2502%2509%250BX%2500%2505%2507%2505%2508Z%250FR%2506%2503%2508%250A%255E%255C%2509VUQ%2501%2504T%255D%2502%2504%250D%250B%2500%2504W%2505VWTTTS%2509U%2506%2507%2506%2506P" + CRLF + CRLF,
						getdata:"ct=upload_api&ac=get_pick_code_info&pickcode="+pickcode+"&version=1176",
                        host: "uapi.115.com",
                        useragent: "115UDownClient 2.1.11.126" 
            }},function(response){
				responseReceived = true;
				//开始处理
				if(  response.code != 0 ){ //插件内部错误
					responseReceived = true;
					var errormessage = response.message || "";
					errormessage += !!errormessage?",":"";
					errormessage += "请尝试<a href=\"https://chrome.google.com/extensions/detail/aiiloiffkhndoefjpciepoldngggnblb\">更新插件</a>或<a href=\"http://t.qq.com/mmplayer\">联系作者</a>解决";
                    jailbreakFail(errormessage);
                    return;
                } //end if

                var response = response.data;
                var state = response.State || response.state;
                var message = response.Message || response.message;
                var urls = response.DownloadUrl;

                if( state && urls ){//成功
                    var download_html = "<div class=\"downloadlinks\">";
                    var ISPlist = ["电信下载","网通下载","备份下载"]
                    for(var i=0,l=urls.length;i<l;i++){
                        download_html +="<a href=\"";
                        download_html +=urls[i].Url;
                        download_html +="\">";
                        download_html +=ISPlist[i]?ISPlist[i]:"其它下载";
                        download_html +="</a>";
                    }
                    download_html+="</div>";
                    jailbreakSuccess(download_html);
    		    }else{//失败
                    jailbreakFail(message);
    		    }

                });
    }//end if
})();
